{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training accuracy is 0.9666666666666667\n",
      "Test accuracy is 0.9666666666666667\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "import copy\n",
    "from sklearn import datasets\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "iris = datasets.load_iris()\n",
    "X = iris.data \n",
    "y = iris.target\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)\n",
    "\n",
    "\n",
    "neigh = KNeighborsClassifier(n_neighbors=3)\n",
    "neigh.fit(X_train, y_train)\n",
    "print(\"Training accuracy is %s\"% neigh.score(X_train,y_train))\n",
    "print(\"Test accuracy is %s\"% neigh.score(X_test,y_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training accuracy is 0.9666666666666667\n",
      "Test accuracy is 0.9666666666666667\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from math import sqrt\n",
    "from collections import Counter\n",
    "\n",
    "# Implement kNN in details\n",
    "def kNNClassify(K, X_train, y_train, X_predict):\n",
    "    distances = [sqrt(np.sum((x - X_predict)**2)) for x in X_train]\n",
    "    sort = np.argsort(distances)\n",
    "    topK = [y_train[i] for i in sort[:K]]\n",
    "    votes = Counter(topK)\n",
    "    y_predict = votes.most_common(1)[0][0]\n",
    "    return y_predict\n",
    "\n",
    "def kNN_predict(K, X_train, y_train, X_predict, y_predict):\n",
    "    acc = 0\n",
    "    for i in range(len(X_predict)):\n",
    "        if y_predict[i] == kNNClassify(K, X_train, y_train, X_predict[i]):\n",
    "            acc += 1\n",
    "    print(acc/len(X_predict))\n",
    "\n",
    "print(\"Training accuracy is \", end='')\n",
    "kNN_predict(3, X_train, y_train, X_train, y_train)\n",
    "print(\"Test accuracy is \", end='')\n",
    "kNN_predict(3, X_train, y_train, X_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "original data:  [10.2  3.4  2.4  2.3]\n",
      "original label:  2\n",
      "attack data:  [8.2 3.4 2.4 2.3]\n",
      "predict label:  1\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import itertools\n",
    "import copy \n",
    "\n",
    "# Attack on KNN\n",
    "def kNN_attack(K, X_train, y_train, X_predict, y_predict): \n",
    "    m = np.diag([0.5,0.5,0.5,0.5])*4\n",
    "    flag = True\n",
    "    for i in range(1,5):\n",
    "        for ii in list(itertools.combinations([0,1,2,3],i)):\n",
    "            delta = np.zeros(4)\n",
    "            for jj in ii:\n",
    "                delta += m[jj]\n",
    "                \n",
    "            if y_predict != kNNClassify(K, X_train, y_train, copy.deepcopy(X_predict)+delta):\n",
    "                X_predict += delta\n",
    "                flag = False\n",
    "                break\n",
    "                \n",
    "            if y_predict != kNNClassify(K, X_train, y_train, copy.deepcopy(X_predict)-delta):\n",
    "                X_predict -= delta\n",
    "                flag = False\n",
    "                break\n",
    "        if not flag:\n",
    "            break\n",
    "            \n",
    "    print('attack data: ',X_predict)\n",
    "    print('predict label: ',kNNClassify(K, X_train, y_train, X_predict))\n",
    "\n",
    "X_test_ = X_test[0]\n",
    "y_test_ = y_test[0]\n",
    "print('original data: ', X_test_)\n",
    "print('original label: ', y_test_)\n",
    "kNN_attack(3, X_train, y_train, X_test_, y_test_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
